package com.hfi.observer.demo06;

import java.util.Observable;
import java.util.Observer;

/**
 * 使用java util下的类 实现推模式
 * @author ChangLiang
 * @date 2019/12/2
 */
class NBAObserver implements Observer{

    private String name;
    
    private Observable notifier;

    public NBAObserver(String name, Observable notifier) {
        this.name = name;
        this.notifier = notifier;
    }

    @Override
    public void update(Observable o, Object arg) {
        System.out.println( ((Boss)o).getAction() + " " + name + "关闭NBA，继续工作 ");    
    }
}

class StockObserver implements Observer {

    private String name;
    private Observable notifier;

    public StockObserver(String name, Observable notifier) {
        this.name = name;
        this.notifier = notifier;
    }

    @Override
    public void update(Observable o, Object arg) {
        System.out.println(((Boss)o).getAction() + " " + name + "关闭股票行情，继续工作 ");
    }
}

class Boss extends Observable {

    @Override
    protected synchronized void setChanged() {
        super.setChanged();
    }

    //要观察的状态
    private String action;

    public void setAction(String action) {
        this.action = action;
    }

    public String getAction() {
        return action;
    }
}


public class Test {
    public static void main(String[] args) {
        Boss huhansan = new Boss();

        StockObserver tongshi1 = new StockObserver("魏关姹", huhansan);
        NBAObserver tongshi2 = new NBAObserver("易管查", huhansan);

        // 注册两位同事
        huhansan.addObserver(tongshi1);
        huhansan.addObserver(tongshi2);
        // 解除注册一位同事
        huhansan.deleteObserver(tongshi1);
        // 发现老板回来
        huhansan.setAction("我胡汉三回来了！");
        // 通知
        // 触发通知的方式有一点变化，要先调用setChanged方法，这个是Java为了帮助实现更精确的触发控制而提供的功能
        huhansan.setChanged();
        huhansan.notifyObservers();
    }
}
